/*
 * @Description: 原文导入规则 - 文件导入规则表格
 * @Author: Rfan
 * @Date: 2022-05-07 17:34:26
 * @LastEditTime: 2022-05-24 14:29:33
 */

import { useEffect } from 'react';
import { Button, Form, Input, message, Radio, Select, Space } from 'antd';
import { MinusCircleOutlined, PlusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { confirmReceive } from '@/api/accession';
import { useBatchManageContext } from '../../../../contexts/BatchManageContext';
import { useReceiveDialogContext } from '../contexts/ReceiveDialogContext';

const { Option } = Select;
const NameForm = (props: any) => {
  const { form, data, metadata = [] } = props;
  const { activeBatch, updateBatchList } = useBatchManageContext();
  const { templateId, onClose } = useReceiveDialogContext();

  useEffect(() => {
    console.log('name effect', data);

    if (data) {
      form.setFieldsValue(data);
    }
  }, [data]);

  const onFinish = (vals: any) => {
    vals.realRuleList.forEach((item: any, idx: number) => {
      item.sortNo = idx + 1;
      item.regex = item.regex || '';
    });
    const params: any = { batchId: activeBatch.id, templateId };
    params.originalRule = { ruleType: 2 };
    params.originalRule.fileNameRule = vals;

    confirmReceive(params).then((res) => {
      message.success('保存成功');
      const { data } = res;
      updateBatchList({
        ...activeBatch,
        attOriginalRule: data?.originalRule || {},
        status: data?.status || activeBatch.status,
        templateExcelId: data?.templateExcelId || 0
      });
      onClose();
    });
  };

  return (
    <Form
      form={form}
      name="nameForm"
      initialValues={{ matchType: 0 }}
      autoComplete="off"
      onFinish={onFinish}
    >
      <Form.Item name="matchType" label="以下条件符合">
        <Radio.Group>
          <Radio value={0}>全部</Radio>
          <Radio value={1}>任何</Radio>
        </Radio.Group>
      </Form.Item>
      <Form.List name="realRuleList">
        {(fields, { add, remove }) => (
          <>
            {fields.map((field) => {
              return (
                <div key={field.key}>
                  <Space align="baseline">
                    <Form.Item
                      {...field}
                      key={`${field.key}-2`}
                      name={[field.name, 'fieldName']}
                      rules={[{ required: true, message: '请选择字段' }]}
                    >
                      <Select placeholder="请选择字段" style={{ width: 140 }}>
                        {metadata.map((item: any) => (
                          <Option key={item.field_name} value={item.field_name}>
                            {item.field_desc}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                    <Form.Item {...field} key={`${field.key}-1`} name={[field.name, 'regex']}>
                      <Input placeholder="请填写正则（可选）" />
                    </Form.Item>
                    <MinusCircleOutlined onClick={() => remove(field.name)} />
                    <PlusCircleOutlined onClick={() => add({ level: 1 }, field.name + 1)} />
                  </Space>
                </div>
              );
            })}
            {fields.length === 0 && (
              <Form.Item>
                <Button
                  type="dashed"
                  icon={<PlusOutlined />}
                  block
                  onClick={() => add({ level: 1 })}
                >
                  增加
                </Button>
              </Form.Item>
            )}
          </>
        )}
      </Form.List>
    </Form>
  );
};

export default NameForm;
